<template>
  <div class="contanier">
    <div class="contanier-title">专题管理</div>
    <search-form>
      <template v-slot:formLeft>
        <el-form :inline="true" :model="userFormLine" class="demo-form-inline">
          <el-row>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="专题名称" label-width="80px">
                  <el-input v-model="userFormLine.name" placeholder="请输入专题名称" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="专题类型" label-width="80px">
                  <el-select v-model="userFormLine.categoryId" placeholder="请输入专题类型">
                    <el-option v-for="item in certificateOptions" :key="item.id" :label="item.fullName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template v-slot:formRight>
        <div class="formRight-btn">
          <el-button class="overPosBtn" icon="el-icon-refresh" @click="onRest">重 置
          </el-button>
          <el-button class="set-col-btn" icon="el-icon-search" type="primary" @click="onSearch">查 询
          </el-button>
        </div>
      </template>
    </search-form>
    <div>
      <search-table>
        <template v-slot:daochu>
          <div class="set-table-right">
            <el-button icon="el-icon-folder-add" @click="showDialog(false)">新 增
            </el-button>
          </div>
        </template>
        <template v-slot:biaoge>
          <template>
            <el-table :data="tableData" :header-cell-style="{
              backgroundColor: '#f5f7fa',
              color: '#606266',
            }" class="table-top" style="width: 100%">
              <el-table-column align="center" label="序号" type="index" width="80">
                <template slot-scope="scope">{{ pageSize * (currentPage - 1) + scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column label="专题名称">
                <template slot-scope="scope">{{ scope.row.name }}</template>
              </el-table-column>
              <el-table-column label="专题新建时间" prop="creatorTime" />
              <el-table-column label="状态" prop="enabledMark">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.enabledMark" active-color="#2265EE" inactive-color="#DBDFEA"
                    @change="changeEnabledMark(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="专题类型">
                <template slot-scope="scope">{{ scope.row.categoryId }}</template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="280">
                <template slot-scope="scope">
                  <el-button class="set-table-btn set-table-btn-col" icon="el-icon-set" size="small" type="text"
                    @click.native.prevent="editRow(scope.$index, scope.row)">
                    专题详情编辑
                  </el-button>
                  <el-button class="set-table-btn set-table-btn-col2" icon="el-icon-delete" size="small" type="text"
                    @click.native.prevent="deleteRow(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </template>
        <template v-slot:fenye>
          <div class="set-table-pg-right">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
              :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </template>
      </search-table>
    </div>

    <el-dialog :title="isEdit ? '编辑' : '新增'" :visible.sync="dialogFormVisible" width="585px">
      <el-form ref="formRef" :model="form" style="height: 65vh; overflow-y:scroll; padding-right: 20px;" :rules="rules">
        <el-form-item v-if="isEdit" :label-width="formLabelWidth" label="序号">
          <el-input autocomplete="off" :value="orderNum" disabled />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="专题名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入专题名称" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="专题图片">
          <UploadImage v-model="form.cover" />
          <div><span style="color: red">*</span>此处专题图片供H5首页展示，建议图片尺寸像素：300（宽度）*200（高度）,大小500kb以下</div>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="专题类型" prop="categoryId">
          <el-select v-model="form.categoryId" autocomplete="off" placeholder="请选择专题类型" style="width: 100%;">
            <el-option v-for="item in certificateOptions" :key="item.id" :label="item.fullName" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label-width="formLabelWidth" label="限制时间" prop="limitTime">
          <el-switch v-model="form.limitTime" active-color="#2265EE" inactive-color="#DBDFEA" />
        </el-form-item> -->
        <el-form-item v-if="form.limitTime" :label-width="formLabelWidth" label="开始时间" prop="startDatetime">
          <el-date-picker v-model="form.startDatetime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item v-if="form.limitTime" :label-width="formLabelWidth" label="截止时间" prop="endDatetime">
          <el-date-picker v-model="form.endDatetime" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="说明" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="5" placeholder="请输入介绍" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="资料关联（可多选）">
          <!-- <div @click="SpecialSubjectDialogVisible = true"> -->
          <div @click="openSpecialSubjectDialog">
            <el-input v-model="form1.zlgl" placeholder="请选择资料关联（可多选）"
              suffix-icon="el-icon-arrow-down" />
          </div>
        </el-form-item>
        <SelectCourseMoudle v-if="SpecialSubjectDialogVisible" :closed="down" @selectComplete="selectComplete" />
        <el-form-item :label-width="formLabelWidth" label="">
          <el-table v-if="form.tableData.length > 0" ref="multipleTable" :data="form.tableData" style="width: 100%"
            tooltip-effect="dark" @selection-change="handleSelectionChange1">
            <el-table-column type="selection" width="55" />
            <el-table-column label="资料名称" prop="name" />
            <el-table-column fixed="right" label="" width="100" align="right">
              <template slot-scope="scope">
                <i class="el-icon-remove-outline" style="color: #0147EB;" @click="() => form.tableData.splice(scope.$index, 1)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item :label-width="formLabelWidth" label="技能考试关联"
          :disabled="form.categoryId != '674000011679236741'">
          <div @click="showExamDialog('znks')">
            <el-input v-model="form1.znks" placeholder="请选择技能考试关联"
              suffix-icon="el-icon-arrow-down" :disabled="form.categoryId != '674000011679236741'" />
          </div>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="">
          <el-table v-if="znks.subjectStageRelationList.length > 0" :data="znks.subjectStageRelationList"
            style="width: 100%" tooltip-effect="dark">
            <el-table-column type="selection" width="55" :selectable="() => true" />
            <el-table-column label="考试名称" prop="objectName" />
            <el-table-column fixed="right" label="" width="100">
              <template slot-scope="scope">
                <i class="el-icon-remove-outline"
                  @click="() => znks.subjectStageRelationList.splice(scope.$index, 1)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item :label-width="formLabelWidth" label="理论考试关联"
          :disabled="form.categoryId != '674000011679236741'">
          <div @click="showExamDialog('llks')">
            <el-input v-model="form1.llks" placeholder="请选择理论考试关联"
              suffix-icon="el-icon-arrow-down" :disabled="form.categoryId != '674000011679236741'" />
          </div>
        </el-form-item>

        <el-form-item :label-width="formLabelWidth" label="">
          <el-table v-if="llks.subjectStageRelationList.length > 0" :data="llks.subjectStageRelationList"
            style="width: 100%" tooltip-effect="dark">
            <el-table-column type="selection" width="55" :selectable="() => true" />
            <el-table-column label="考试名称" prop="objectName" />
            <el-table-column fixed="right" label="" width="100">
              <template slot-scope="scope">
                <i class="el-icon-remove-outline"
                  @click="() => llks.subjectStageRelationList.splice(scope.$index, 1)" />
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <selectExamMoudle v-if="selectExamVisible" :closed="down1" @selectComplete="examSelectComplete" />
        <!--
        <el-form-item :label-width="formLabelWidth" label="阶段间闯关">
          <el-switch v-model="form.interphaseChallenges" active-color="#2265EE" inactive-color="#DBDFEA" />
        </el-form-item>

        <h3>通过条件</h3>
        <p style="margin-block: 6px;">当达到设置的值后，培训内容才算完成，以下要求中必须设置一项</p>
        <div class="flex border">
          必修资源要求
          <div style="margin-inline: 10px;">
            <el-switch v-model="form.required" />
          </div>

          在规定的时间内，必修资源需要完成的个数
          <div class="flex step-num">
            <el-input-number v-model="form.requiredCompleted" :disabled="!form.required" controls-position="right"
              :min="1" :max="stepTotal" />/{{ stepTotal }}
          </div>

        </div>

       <h3 style="margin-top: 10px;">可见范围</h3>
        <div class="visibleRange">
          可见类型：
          <el-checkbox-group v-model="form.scope">
            <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.fullName }}</el-checkbox>
          </el-checkbox-group>
        </div> -->
        <!-- <h3>学习奖励</h3>
        <div class="jl">
          <div class="zsmb">证书模版</div>
          <div class="jl-ipt" @click="openSelectCertDialog">
            <el-input :value="form.certificateName" placeholder="请输入">
              <el-button slot="append" @click="openSelectCertDialog">
                选择
              </el-button>
            </el-input>
            <selectCertMoudle v-if="selectCertVisible" :closed="down2" @selectComplete="certSelectComplete" />
          </div>
        </div> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog" style="width: 104px; height: 36px;">取 消</el-button>
        <el-button type="primary" @click="onSubmit1" style="width: 104px; height: 36px;">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showTest" title="提示" width="30%">
      <div class="tip">
        <div class="header">
          <div class="dia-txt">是否确认删除？</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showTest = false" style="width: 104px; height: 36px;">取消</el-button>
        <el-button type="primary" @click="showTest = false" style="width: 104px; height: 36px;">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import SearchForm from '@/components/search-form'
import SearchTable from '@/components/search-table'
import SelectCourseMoudle from '../dataCenter/SelectCourse.vue'
import selectExamMoudle from '../dataCenter/SelectExam.vue'
import selectCertMoudle from '../dataCenter/SelectCert.vue'
import { addTems, deleteZTlist, getZTlist } from '@/api/dataCenter/dataCenterApi'
import { getDictionaryDataSelector, getDictionaryDataList } from '@/api/systemData/dictionary'
import UploadImage from '@/components/UploadImage'
import request from '@/utils/request'

export default {
  name: 'UserManagement',
  components: {
    SearchForm,
    SearchTable,
    SelectCourseMoudle,
    selectExamMoudle,
    selectCertMoudle,
    UploadImage
  },

  data() {
    return {
      showTest: false,
      formLabelWidth: '140px',
      dialogFormVisible: false,
      dialogFormVisible1: false,
      SpecialSubjectDialogVisible: false,
      selectExamVisible: false,
      selectCertVisible: false,
      certificateOptions: [],
      isEdit: false,
      tableData: [],
      tableData1: [],
      roles: [],
      rules: {
        name: [
          { required: true, message: '请输入专题名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择专题类型', trigger: 'change' }
        ],
        // certificateId: [
        //   { required: true, message: '请选择类型', trigger: 'blur' }
        // ],
        // limitTime: [
        //   { required: true, message: '请选择限制时间', trigger: 'blur' }
        // ],
        // startDatetime: [
        //   { required: true, message: '请选择开始时间', trigger: 'blur' }
        // ],
        // endDatetime: [
        //   { required: true, message: '请选择截止时间', trigger: 'blur' }
        // ]
      },
      form: {
        name: '',
        cover: '',
        categoryId: '',
        limitTime: false,
        startDatetime: '',
        endDatetime: '',
        description: '',
        interphaseChallenges: true,
        required: true,
        scope: [],
        certificateId: '',
        certificateName: '',
        tableData: [],
        stageList: []
      },
      form1: {
        name: '',
        ztmc: '',
        zlgl: '',
        znks: '',
        llks: '',
        challenge: 0,
        description: '',
        sortCode: '',
        subjectId: '',
        subjectStageRelationList: [
        ]
      },
      editableTabsValue: '1',
      userFormLine: {
        name: ''
      },
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      value1: false,
      ksName: '',
      znks: {
        challenge: 0,
        description: '',
        sortCode: 1,
        subjectId: '',
        subjectStageRelationList: []
      },
      llks: {
        challenge: 0,
        description: '',
        sortCode: 2,
        subjectId: '',
        subjectStageRelationList: [
        ]
      },
      orderNum: 0,
      editId: ''
    }
  },
  computed: {
    stepTotal() {
      return this.znks.subjectStageRelationList.length + this.llks.subjectStageRelationList.length + this.form.tableData.length
    }
  },
  created() {
    this.getData()
    getDictionaryDataSelector('647319861030053509').then(res => {})
    
    getDictionaryDataList('559344237955514629', {
      keyword: '',
      isTree: 0
    }).then(res => {
      this.certificateOptions = res.data.list
    })

    request({
      url: `api/permission/Role?n=1743175635&organizeId=0&keyword=&currentPage=1&pageSize=20&sort=desc&sidx=&typeList=ApplicationRole&menuId=07029F61-993A-4A46-BF56-20DE382F4F66`,
      method: 'get'
    })
      .then(res => {
        this.roles = res.data.list || []
      })
  },
  methods: {
    onSubmit1() {
      this.$refs.formRef.validate((valid) => {
        if (!valid) {
          return;
        }
        if(this.form.cover.length == 0) {
          this.$message.error('请上传专题图片');
          return;
        }
        if(this.form.categoryId == '673999851997889157') {
          if (this.form.tableData.length == 0) {
            this.$message.error('当专题类型是科普，请选择关联资料');
            return;
          }
        }
        else if (this.form.categoryId == '674000011679236741') {
          if (this.znks.subjectStageRelationList.length == 0) {
            this.$message.error('当专题类型是培训考试，请选择关联技能考试');
            return;
          }
          if (this.llks.subjectStageRelationList.length == 0) {
            this.$message.error('当专题类型是培训考试，请选择关联理论考试');
            return;
          }
        }
        const stageList = [
          {
            challenge: 1,
            description: '',
            sortCode: 0,
            subjectId: '',
            subjectStageRelationList: this.form.tableData.map(item => ({
              objectId: item.id,
              objectName: item.name,
              objectType: 'Course',
              sortCode: 0,
              type: '2',
              cover: item.cover
            }))
          }
        ]

        if (this.form.categoryId == '674000011679236741') {
          stageList.push(this.znks, this.llks)
        }

        const data = {
          'categoryId': '',
          'certificateId': '',
          'cover': '',
          'creatorUserId': '',
          'description': '',
          'docsLearning': '',
          'docsLearningLength': 0,
          'elective': '',
          'electiveCompleted': 0,
          'electiveTotal': 0,
          'enabledMark': 1,
          'medalId': '',
          'name': '',
          'overdueLearning': '',
          'scopeType': 'all',
          'syncProgress': '',
          ...this.form,
          'requiredCompleted': this.stepTotal,
          startDatetime: 0,
          endDatetime: 0,
          interphaseChallenges: this.form.interphaseChallenges ? 1 : 0,
          limitTime: 0,
          required: this.form.required ? 1 : 0,
          stageList,
          'requiredTotal': this.stepTotal,
          scope: JSON.stringify([{
            type: 'Role', selectArr: []
          }]),
          scopeRoles: ''
        }

        delete data.tableData

        console.log(data,'---data----111')


        if (this.isEdit) {
          request({
            url: '/api/course/TemsSubject/' + this.editId,
            method: 'put',
            data
          }).then(() => {
            this.dialogFormVisible = false
            this.$refs.formRef.resetFields()
            this.resetFormData()
            this.getData()
          })
        } else {
          addTems(data)
            .then(() => {
              this.dialogFormVisible = false
              this.$refs.formRef.resetFields()
              this.resetFormData()
              this.getData()
            })
            .catch((e) => {
              console.log(e)
            })
        }
      });
    },
    onRest() {
      this.userFormLine = {
        name: '',
        categoryId: ''
      }
      this.currentPage = 1
      this.getData()
    },
    onSearch() {
      this.currentPage = 1
      this.getData()
    },
    getData() {
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        ...this.userFormLine
      }
      getZTlist(params)
        .then((res) => {
          console.log('专题列表', res)
          this.tableData = res.data.list.map(item => ({
            ...item,
            enabledMark: Boolean(parseInt(item.enabledMark))
          }))
          this.total = res.data.pagination.total
        })
        .catch((e) => {
        })
    },
    deleteRow(row) {
      // this.showTest = true;
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteZTlist(row.id).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.onSearch()
        })
      })
    },
    showExamDialog(name) {
      if (this.form.categoryId !== '674000011679236741') return
      this.ksName = name
      // this.dialogFormVisible1 = true
      this.selectExamVisible = true
    },
    handleSelectionChange1(val) {
      this.multipleSelection1 = val
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.currentPage = 1
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getData()
    },
    editRow(i, row) {
      this.orderNum = i + 1
      this.isEdit = true
      this.dialogFormVisible = true
      this.editId = row.id
      request({
        url: '/api/course/TemsSubject/' + row.id,
        method: 'get'
      })
      .then(res => {
        const { data } = res
        if (data.categoryId == '674000011679236741') {
          // 培训
          this.znks = data.stageList[1]
          this.llks = data.stageList[2]
        }
        this.form = Object.assign(
          {},
          this.form,
          data,
          {
            limitTime: data.limitTime === '1',
            interphaseChallenges: data.interphaseChallenges === '1',
            required: data.required === '1',
            tableData: data.stageList[0].subjectStageRelationList.map(item => ({
              ...item,
              id: item.objectId,
              name: item.objectName
            }))

          }
        )
      })
    },
    openSpecialSubjectDialog() {
      this.SpecialSubjectDialogVisible = true
    },
    down() {
      this.SpecialSubjectDialogVisible = false
    },
    openSelectExamDialog() {
      this.selectExamVisible = true
    },
    down1() {
      this.selectExamVisible = false
      this.confirmJDDialog()
    },
    openSelectCertDialog() {
      this.selectCertVisible = true
    },
    down2() {
      this.selectCertVisible = false
    },
    selectComplete(multipleSelection) {
      for (let i = 0; i < multipleSelection.length; i++) {
        const item = multipleSelection[i];
        if (!this.form.tableData.find((item1) => item1.id === item.id)) {
          this.form.tableData.push(item)
        }
      }
    },
    examSelectComplete(multipleSelection) {
      this.tableData1 = multipleSelection
    },
    certSelectComplete(multipleSelection) {
      this.form.certificateName = multipleSelection.slice(-1).map(item => item.name).join(',')
      this.form.certificateId = multipleSelection.slice(-1).map(item => item.id).join(',')
    },
    cancelJDDialog() {
      this.dialogFormVisible1 = false
      // this.$refs.form1Ref.resetFields()
      this.tableData1 = []
    },
    confirmJDDialog() {
      this.dialogFormVisible1 = false
      if (this.ksName === 'znks') {
        for (let i = 0; i < this.tableData1.length; i++) {
          const item = this.tableData1[i];
          if (!this.znks.subjectStageRelationList.find(item1 => item1.objectId === item.id)) {
            this.znks.subjectStageRelationList.push({
              objectId: item.id,
              objectName: item.fullName,
              objectType: 'Exam',
              sortCode: 1,
              type: '2'
            })
          }
        }
      } else if (this.ksName === 'llks') {
        for (let i = 0; i < this.tableData1.length; i++) {
          const item = this.tableData1[i];
          if (!this.llks.subjectStageRelationList.find(item1 => item1.objectId === item.id)) {
            this.llks.subjectStageRelationList.push({
              objectId: item.id,
              objectName: item.fullName,
              objectType: 'Exam',
              sortCode: 2,
              type: '2'
            })
          }
        }
      }
      // this.$refs.form1Ref.resetFields()
      this.tableData1 = []
    },
    cancelDialog() {
      this.$refs.formRef.resetFields()
      this.dialogFormVisible = false
      this.resetFormData()
    },
    showDialog(isEdit) {
      this.isEdit = isEdit
      this.dialogFormVisible = true
    },
    resetFormData() {
      this.form = {
        name: '',
        cover: '',
        categoryId: '',
        limitTime: false,
        startDatetime: '',
        endDatetime: '',
        description: '',
        interphaseChallenges: true,
        required: false,
        scope: [],
        certificateId: '',
        certificateName: '',
        tableData: [],
        stageList: []
      }
      this.znks = {
        challenge: 0,
        description: '',
        sortCode: 1,
        subjectId: 1,
        subjectStageRelationList: []
      }
      this.llks = {
        challenge: 0,
        description: '',
        sortCode: 2,
        subjectId: '',
        subjectStageRelationList: [
        ]
      }
    },
    changeEnabledMark(item) {
      request({
        url: `/api/course/TemsSubject/updateEnabledMark/${item.id}/${item.enabledMark ? 1 : 0}`,
        method: 'put',
      }).finally(() => {
        this.getData()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-icon-set {
  background: url("../../assets/learning/peizhi.png") no-repeat;
  width: 20px;
  height: 20px;
  transform: translateY(4px) translateX(2px);
}

::v-deep .el-icon-set:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-set {
  font-size: 18px;
}

::v-deep .el-icon-set:before {
  content: "\e611";
}

.study-content {
  margin-bottom: 10px;
}

.visibleRange {
  margin-top: 20px;
  margin-bottom: 10px;
  display: flex;
}

.jl {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  .zsmb {
    width: 10%;
  }

  .jl-ipt {
    width: 100%;
  }
}

.flex {
  display: flex;
  align-items: center;
}

.border {
  padding-inline: 8px;
  padding-block: 18px;
  border: 1px solid rgb(240, 240, 240);
}

.step-num {
  justify-content: flex-end;
  flex: 1;
  margin-right: 20px;
}
</style>
